package com.yx.system.service.impl;

import com.yx.common.utils.R;
import com.yx.modules.api.dao.SysAuthBookDao;
import com.yx.modules.api.dao.TbVolumeDao;
import com.yx.modules.api.entity.TbVolume;
import com.yx.system.authEntity.SysAuthSection;
import com.yx.system.authEntity.SysAuthText;
import com.yx.system.dao.*;
import com.yx.system.entity.*;
import com.yx.system.service.SysAuthBookInfoService;
import com.yx.utils.AmountUtils;
import com.yx.utils.ContextUtil;
import com.yx.utils.HttpUtil;
import com.yx.utils.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Service
public class SysAuthBookInfoServiceImpl implements SysAuthBookInfoService {
    @Autowired
    private SysAuthBookInfoDao authBookInfoDao;
    @Autowired
    private SysAuthBookDao sysAuthBookDao;
    @Autowired
    private TdCategoryMapper tdCategoryMapper;
    @Autowired
    private TdBookMapper tdBookMapper;
    @Autowired
    private TbVolumeDao tbVolumeDao;
    @Autowired
    private SysPriceDao sysPriceDao;
    @Autowired
    private TdTextMapper tdTextMapper;
    @Autowired
    private TdSectionMapper tdSectionMapper;

    @Override
    public SysAuthBookInfo queryObject(String id) {
        return authBookInfoDao.queryObject(id);
    }

    @Override
    public List<SysAuthBookInfo> queryList(Map<String, Object> map) {
        return authBookInfoDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return authBookInfoDao.queryTotal(map);
    }

    @Override
    public void save(SysAuthBookInfo authBookInfo) {
        authBookInfoDao.save(authBookInfo);
    }

    @Override
    public void update(SysAuthBookInfo authBookInfo) {
        authBookInfoDao.update(authBookInfo);
    }

    @Override
    public void delete(String id) {
        authBookInfoDao.delete(id);
    }

    @Override
    public R deleteBatch(String[] ids) {
        for (String arr:ids){
            //找到对应第三方图书详情数据
            SysAuthBookInfo sysAuthBookInfo = authBookInfoDao.queryObject(arr);
            //找到对应的第三方图书
            SysAuthBook sysAuthBook = sysAuthBookDao.queryObject(arr);
            //根据第三方图书找到图书对象
            TdBook tdBook = tdBookMapper.findByUUID(sysAuthBookInfo.getUuid());
            if (tdBook==null){
                return R.error("未找到图书数据");
            }
            //找到对应的卷
            List<TbVolume> tbVolumes = tbVolumeDao.findByBookId(tdBook.getId());
            if (tbVolumes.size()!=0){
                for (TbVolume tbVolume:tbVolumes){
                    tbVolumeDao.delete(tbVolume.getId());
                }
            }
            List<TdSection> tdSectionList = tdSectionMapper.findByBookid(tdBook.getId());
            //循环章节找到内容一起删除
            if (tdSectionList.size()!=0){
                for (TdSection tdSection1 : tdSectionList) {
                    //找到对应的TEXT
                    TdText tdText1 = tdTextMapper.findByUid(tdSection1.getUuid());
                    if (tdText1!=null){
                        tdTextMapper.deleteByPrimaryKey(tdText1.getId());
                    }
                    //开始删除
                    tdSectionMapper.deleteByPrimaryKey(tdSection1.getId());
                }
            }
            //删除图书及第三方数据
            tdBookMapper.deleteByPrimaryKey(tdBook.getId());
            authBookInfoDao.deleteById(sysAuthBookInfo.getId());
            sysAuthBookDao.deleteById(sysAuthBook.getId());
        }
        return R.ok();
    }

    @Override
    @Transactional
    public R put(SysAuthBookInfo authBookInfo, SysUser sysUser) {
        //取出一级分类id,并查询
        Integer categoryid = authBookInfo.getCid();
        TdCategory tdCategory = tdCategoryMapper.selectByPrimaryKey(categoryid);
        //取出章节收费
        List<SysPrice> sysPrices = sysPriceDao.findAll();
        /*if (sysPrices.size() > 1 || sysPrices.size() == 0) {
            return R.error("请先设置章节收费，并只能存在一条");
        }*/
        SysPrice sysPrice = sysPrices.get(0);
        //初始化字数计算正则
        String regex = "[\u4e00-\u9fff]";
        //判断图书是否已经导入过了
        try {
            if (authBookInfo.getStatus() == 0) {
            /*===============================图书==========================================*/
                //新建图书对象
                TdBook tdBook = new TdBook();
                //生成一个随机唯一标识
                String arr = OrderUtil.getNumberForPK();
                //注入值
                tdBook.setCreatedate(new Date());
                tdBook.setUpdatedate(new Date());
                tdBook.setBookname(authBookInfo.getName());
                tdBook.setPicurl(authBookInfo.getCover());
                tdBook.setBooknum((int) Math.random());
                tdBook.setCategoryid(categoryid);
                tdBook.setCategoryname(tdCategory.getCategoryyname());
                tdBook.setBookno(arr);
                tdBook.setClassificationid(0);
                tdBook.setClassificationname("");
                if (authBookInfo.getIs_vip().equals("Y")) {
                    tdBook.setIspay(true);
                } else {
                    tdBook.setIspay(false);
                }
                if (authBookInfo.getComplete_status().equals("Y")) {
                    tdBook.setIsserialize(false);
                } else {
                    tdBook.setIsserialize(true);
                }
                tdBook.setAuthorCode("0");
                tdBook.setAuthorName(authBookInfo.getAuthor());
                tdBook.setIsxianyan(false);
                tdBook.setIsxianjie(false);
                tdBook.setIswuxia(false);
                tdBook.setIssanjie(false);
                tdBook.setIsremen(false);
                tdBook.setIsqihuan(false);
                tdBook.setIsjingxuan(false);
                tdBook.setIsgongting(false);
                tdBook.setIsdelete(false);
                tdBook.setChecknum(0);
                tdBook.setIntroduction(authBookInfo.getBrief());
                tdBook.setSell(0);
                tdBook.setGrade(Double.valueOf(0));
                tdBook.setGradeSum(Double.valueOf(0));
                tdBook.setGradeNumber(0);
                tdBook.setWordType(0);
                tdBook.setLikeCount(0);
                tdBook.setCollectionCount(0);
                tdBook.setRewardCount(0);
                tdBook.setRewardMoney(0);
                tdBook.setCommentCount(0);
                tdBook.setCommentBoyCount(0);
                tdBook.setCommentGirlCount(0);
                tdBook.setFontCount(0);
                tdBook.setSectionNumber(0);
                tdBook.setBooktype(1);
                //保存图书
                tdBookMapper.insert(tdBook);
                //改变第三方书籍属性并保存
                authBookInfo.setStatus(1);
                authBookInfo.setUpdateDate(new Date());
                authBookInfo.setUuid(arr);
                authBookInfoDao.update(authBookInfo);
			/*====================================卷和章节==============================================*/
                //获取第三方接口的第三方章节集合
                String id = authBookInfo.getId();
                String sign = HttpUtil.encryption("49MTUzMTE5MDA5MjM5MQ" + id);
                String temp = HttpUtil.sendGet("http://www.quyuewang.cn/api.php/ChapterList/index/" + id + "?client_id=49&sign=" + sign);
                List<SysAuthSection> sysAuthBooks = HttpUtil.jsonToList(temp, SysAuthSection.class);
                //循环所有第三方章节
                for (SysAuthSection sysAuthSection : sysAuthBooks) {
                    //根据卷id去查询数据库，是否存在,不存在就新建
                    Integer volumeid = Integer.valueOf(sysAuthSection.getV_id()) * 100;
                    TbVolume tbVolume = tbVolumeDao.queryObject(volumeid);
                    if (tbVolume == null) {
                        tbVolume = new TbVolume();
                        tbVolume.setId(volumeid);
                        tbVolume.setVolumeName(sysAuthSection.getV_title());
                        tbVolume.setBookId(tdBook.getId());
                        tbVolume.setBookName(tdBook.getBookname());
                        tbVolume.setCreateDate(new Date());
                        tbVolume.setUpdateDate(new Date());
                        tbVolumeDao.save(tbVolume);
                    }
                    //创建章节对象赋值
                    TdSection tdSection = new TdSection();
                    tdSection.setUuid(UUID.randomUUID().toString());
                    tdSection.setSectionname(sysAuthSection.getName());
                    tdSection.setSectionno((int) Math.random());
                    tdSection.setCreatedate(new Date());
                    tdSection.setCreateuser(sysUser.getUsername());
                    tdSection.setUpdatedate(new Date());
                    tdSection.setUpdateuser(sysUser.getUsername());
                    tdSection.setPicurl(tdBook.getPicurl());
                    if (sysAuthSection.getIs_free() == 0) {
                        tdSection.setSectionType(1);
                        tdSection.setTotalfee(sysPrice.getPrice());
                    } else {
                        tdSection.setSectionType(0);
                        tdSection.setTotalfee(0);
                    }
                    tdSection.setIsdelete(false);
                    tdSection.setBookid(tdBook.getId());
                    tdSection.setVolumeId(tbVolume.getId());
                    tdSection.setVolumeName(tbVolume.getVolumeName());
                    tdSection.setFontsize(0);
                    //保存章节
                    tdSectionMapper.insert(tdSection);
                    //图书设置最新章节并保存
                    tdBook.setNewsectionid(tdSection.getId());
                    tdBook.setNewsection(tdSection.getSectionname());
                    tdBookMapper.updateByPrimaryKey(tdBook);
                /*=====================================章节内容========================================*/
                    //获取对应第三方章节内容
                    String sign1 = HttpUtil.encryption("49MTUzMTE5MDA5MjM5MQ" + id + sysAuthSection.getId());
                    String temp1 = HttpUtil.sendGet("http://www.quyuewang.cn/api.php/ChapterInfo/index/" + id + "/" + sysAuthSection.getId() + "?client_id=49&sign=" + sign1);
                    SysAuthText sysAuthText = HttpUtil.tobean(temp1, SysAuthText.class);
                    //初始化Text对象
                    TdText tdText = new TdText();
                    //赋值
                    tdText.setId(UUID.randomUUID().toString());
                    tdText.setUid(tdSection.getUuid());
                    tdText.setBookname(tdBook.getBookname());
                    tdText.setSection(tdSection.getSectionname());
                    tdText.setAuthor(tdBook.getAuthorName());
                    tdText.setCreatetime(new Date());
                    tdText.setIsdelete(0);
                    tdText.setText(sysAuthText.getContent());
                    //保存
                    tdTextMapper.insert(tdText);
                    //修改章节属性并更新
                    int count = (" " + tdText.getText() + " ").split(regex).length - 1;
                    tdSection.setFontsize(count);
                    tdSectionMapper.updateByPrimaryKey(tdSection);
                }
                return R.ok().put("msg", "导入成功");
            }
            //导入过
            else {
                //通过对应的uuid找到图书
                TdBook tdBook = tdBookMapper.findByUUID(authBookInfo.getUuid());
                /*
                *===============================================================================================
                */
                if (tdBook == null) {
                    //新建图书对象
                    tdBook = new TdBook();
                    //生成一个随机唯一标识
                    String arr = OrderUtil.getNumberForPK();
                    //注入值
                    tdBook.setCreatedate(new Date());
                    tdBook.setUpdatedate(new Date());
                    tdBook.setBookname(authBookInfo.getName());
                    tdBook.setPicurl(authBookInfo.getCover());
                    tdBook.setBooknum((int) Math.random());
                    tdBook.setCategoryid(categoryid);
                    tdBook.setCategoryname(tdCategory.getCategoryyname());
                    tdBook.setBookno(arr);
                    tdBook.setClassificationid(0);
                    tdBook.setClassificationname("");
                    if (authBookInfo.getIs_vip().equals("Y")) {
                        tdBook.setIspay(true);
                    } else {
                        tdBook.setIspay(false);
                    }
                    if (authBookInfo.getComplete_status().equals("Y")) {
                        tdBook.setIsserialize(false);
                    } else {
                        tdBook.setIsserialize(true);
                    }
                    tdBook.setAuthorCode("0");
                    tdBook.setAuthorName(authBookInfo.getAuthor());
                    tdBook.setIsxianyan(false);
                    tdBook.setIsxianjie(false);
                    tdBook.setIswuxia(false);
                    tdBook.setIssanjie(false);
                    tdBook.setIsremen(false);
                    tdBook.setIsqihuan(false);
                    tdBook.setIsjingxuan(false);
                    tdBook.setIsgongting(false);
                    tdBook.setIsdelete(false);
                    tdBook.setChecknum(0);
                    tdBook.setIntroduction(authBookInfo.getBrief());
                    tdBook.setSell(0);
                    tdBook.setGrade(Double.valueOf(0));
                    tdBook.setGradeSum(Double.valueOf(0));
                    tdBook.setGradeNumber(0);
                    tdBook.setWordType(0);
                    tdBook.setLikeCount(0);
                    tdBook.setCollectionCount(0);
                    tdBook.setRewardCount(0);
                    tdBook.setRewardMoney(0);
                    tdBook.setCommentCount(0);
                    tdBook.setCommentBoyCount(0);
                    tdBook.setCommentGirlCount(0);
                    tdBook.setFontCount(0);
                    tdBook.setSectionNumber(0);
                    tdBook.setBooktype(1);
                    //保存图书
                    tdBookMapper.insert(tdBook);
                    //改变第三方书籍属性并保存
                    authBookInfo.setStatus(1);
                    authBookInfo.setUpdateDate(new Date());
                    authBookInfo.setUuid(arr);
                    authBookInfoDao.update(authBookInfo);
			/*====================================卷和章节==============================================*/
                    //获取第三方接口的第三方章节集合
                    String id = authBookInfo.getId();
                    String sign = HttpUtil.encryption("49MTUzMTE5MDA5MjM5MQ" + id);
                    String temp = HttpUtil.sendGet("http://www.quyuewang.cn/api.php/ChapterList/index/" + id + "?client_id=49&sign=" + sign);
                    List<SysAuthSection> sysAuthBooks = HttpUtil.jsonToList(temp, SysAuthSection.class);
                    //循环所有第三方章节
                    for (SysAuthSection sysAuthSection : sysAuthBooks) {
                        //根据卷id去查询数据库，是否存在,不存在就新建
                        Integer volumeid = Integer.valueOf(sysAuthSection.getV_id()) * 100;
                        TbVolume tbVolume = tbVolumeDao.queryObject(volumeid);
                        if (tbVolume == null) {
                            tbVolume = new TbVolume();
                            tbVolume.setId(volumeid);
                            tbVolume.setVolumeName(sysAuthSection.getV_title());
                            tbVolume.setBookId(tdBook.getId());
                            tbVolume.setBookName(tdBook.getBookname());
                            tbVolume.setCreateDate(new Date());
                            tbVolume.setUpdateDate(new Date());
                            tbVolumeDao.save(tbVolume);
                        }
                        //创建章节对象赋值
                        TdSection tdSection = new TdSection();
                        tdSection.setUuid(UUID.randomUUID().toString());
                        tdSection.setSectionname(sysAuthSection.getName());
                        tdSection.setSectionno((int) Math.random());
                        tdSection.setCreatedate(new Date());
                        tdSection.setCreateuser(sysUser.getUsername());
                        tdSection.setUpdatedate(new Date());
                        tdSection.setUpdateuser(sysUser.getUsername());
                        tdSection.setPicurl(tdBook.getPicurl());
                        if (sysAuthSection.getIs_free() == 0) {
                            tdSection.setSectionType(1);
                            tdSection.setTotalfee(sysPrice.getPrice());
                        } else {
                            tdSection.setSectionType(0);
                            tdSection.setTotalfee(0);
                        }
                        tdSection.setIsdelete(false);
                        tdSection.setBookid(tdBook.getId());
                        tdSection.setVolumeId(tbVolume.getId());
                        tdSection.setVolumeName(tbVolume.getVolumeName());
                        tdSection.setFontsize(0);
                        //保存章节
                        tdSectionMapper.insert(tdSection);
                        //图书设置最新章节并保存
                        tdBook.setNewsectionid(tdSection.getId());
                        tdBook.setNewsection(tdSection.getSectionname());
                        tdBookMapper.updateByPrimaryKey(tdBook);
                /*=====================================章节内容========================================*/
                        //获取对应第三方章节内容
                        String sign1 = HttpUtil.encryption("49MTUzMTE5MDA5MjM5MQ" + id + sysAuthSection.getId());
                        String temp1 = HttpUtil.sendGet("http://www.quyuewang.cn/api.php/ChapterInfo/index/" + id + "/" + sysAuthSection.getId() + "?client_id=49&sign=" + sign1);
                        SysAuthText sysAuthText = HttpUtil.tobean(temp1, SysAuthText.class);
                        //初始化Text对象
                        TdText tdText = new TdText();
                        //赋值
                        tdText.setId(UUID.randomUUID().toString());
                        tdText.setUid(tdSection.getUuid());
                        tdText.setBookname(tdBook.getBookname());
                        tdText.setSection(tdSection.getSectionname());
                        tdText.setAuthor(tdBook.getAuthorName());
                        tdText.setCreatetime(new Date());
                        tdText.setIsdelete(0);
                        tdText.setText(sysAuthText.getContent());
                        //保存
                        tdTextMapper.insert(tdText);
                        //修改章节属性并更新
                        int count = (" " + tdText.getText() + " ").split(regex).length - 1;
                        tdSection.setFontsize(count);
                        tdSectionMapper.updateByPrimaryKey(tdSection);
                    }

                }else {

                    //更新属性并更新
                    tdBook.setCategoryid(categoryid);
                    tdBook.setCategoryname(tdCategory.getCategoryyname());
                    if (authBookInfo.getIs_vip().equals("Y")) {
                        tdBook.setIspay(true);
                    } else {
                        tdBook.setIspay(false);
                    }
                    if (authBookInfo.getComplete_status().equals("Y")) {
                        tdBook.setIsserialize(false);
                    } else {
                        tdBook.setIsserialize(true);
                    }
                    tdBook.setBookname(authBookInfo.getName());
                    tdBook.setPicurl(authBookInfo.getCover());
                    tdBook.setAuthorName(authBookInfo.getAuthor());
                    tdBook.setIntroduction(authBookInfo.getBrief());
                    tdBook.setBooktype(1);
                    tdBookMapper.updateByPrimaryKey(tdBook);
                    //改变第三方书籍属性并更新
                    authBookInfo.setUpdateDate(new Date());
                    authBookInfo.setStatus(1);
                    authBookInfoDao.update(authBookInfo);
			/*
			* 先找出图书下的所有卷和章节和内容进行删除
			*/      List<TbVolume> tbVolumes = tbVolumeDao.findByBookId(tdBook.getId());
			        if (tbVolumes.size()!=0){
			            for (TbVolume tbVolume:tbVolumes){
			                tbVolumeDao.delete(tbVolume.getId());
                        }
                    }
                    List<TdSection> tdSectionList = tdSectionMapper.findByBookid(tdBook.getId());
                    //循环章节找到内容一起删除
                    if (tdSectionList.size()!=0){
                        for (TdSection tdSection1 : tdSectionList) {
                            //找到对应的TEXT
                            TdText tdText1 = tdTextMapper.findByUid(tdSection1.getUuid());
                            //开始删除
                            if (tdText1!=null){
                                tdTextMapper.deleteByPrimaryKey(tdText1.getId());
                            }
                            tdSectionMapper.deleteByPrimaryKey(tdSection1.getId());
                        }
                    }
            /*
            * 开始重新添加章节和内容
            */
            /*====================================卷和章节==============================================*/
                    //获取第三方接口的第三方章节集合
                    String id3 = authBookInfo.getId();
                    String sign3 = HttpUtil.encryption("49MTUzMTE5MDA5MjM5MQ" + id3);
                    String temp3 = HttpUtil.sendGet("http://www.quyuewang.cn/api.php/ChapterList/index/" + id3 + "?client_id=49&sign=" + sign3);
                    List<SysAuthSection> sysAuthBooks3 = HttpUtil.jsonToList(temp3, SysAuthSection.class);
                    //循环所有第三方章节
                    for (SysAuthSection sysAuthSection : sysAuthBooks3) {
                        //根据卷id去查询数据库，是否存在,不存在就新建
                        Integer volumeid = Integer.valueOf(sysAuthSection.getV_id()) * 100;
                        TbVolume tbVolume = tbVolumeDao.queryObject(volumeid);
                        if (tbVolume == null) {
                            tbVolume = new TbVolume();
                            tbVolume.setId(volumeid);
                            tbVolume.setVolumeName(sysAuthSection.getV_title());
                            tbVolume.setBookId(tdBook.getId());
                            tbVolume.setBookName(tdBook.getBookname());
                            tbVolume.setCreateDate(new Date());
                            tbVolume.setUpdateDate(new Date());
                            tbVolumeDao.save(tbVolume);
                        }
                        //创建章节对象赋值
                        TdSection tdSection = new TdSection();
                        tdSection.setUuid(UUID.randomUUID().toString());
                        tdSection.setSectionname(sysAuthSection.getName());
                        tdSection.setSectionno((int) Math.random());
                        tdSection.setCreatedate(new Date());
                        tdSection.setCreateuser(sysUser.getUsername());
                        tdSection.setUpdatedate(new Date());
                        tdSection.setUpdateuser(sysUser.getUsername());
                        tdSection.setPicurl(tdBook.getPicurl());
                        if (sysAuthSection.getIs_free() == 0) {
                            tdSection.setSectionType(1);
                            tdSection.setTotalfee(sysPrice.getPrice());
                        } else {
                            tdSection.setSectionType(0);
                            tdSection.setTotalfee(0);
                        }
                        tdSection.setIsdelete(false);
                        tdSection.setBookid(tdBook.getId());
                        tdSection.setVolumeId(tbVolume.getId());
                        tdSection.setVolumeName(tbVolume.getVolumeName());
                        tdSection.setFontsize(0);
                        //保存章节
                        tdSectionMapper.insert(tdSection);
                        //图书设置最新章节并保存
                        tdBook.setNewsectionid(tdSection.getId());
                        tdBook.setNewsection(tdSection.getSectionname());
                        tdBookMapper.updateByPrimaryKey(tdBook);
                /*=====================================章节内容========================================*/
                        //获取对应第三方章节内容
                        String sign1 = HttpUtil.encryption("49MTUzMTE5MDA5MjM5MQ" + id3 + sysAuthSection.getId());
                        String temp1 = HttpUtil.sendGet("http://www.quyuewang.cn/api.php/ChapterInfo/index/" + id3 + "/" + sysAuthSection.getId() + "?client_id=49&sign=" + sign1);
                        SysAuthText sysAuthText = HttpUtil.tobean(temp1, SysAuthText.class);
                        //初始化Text对象
                        TdText tdText = new TdText();
                        //赋值
                        tdText.setId(UUID.randomUUID().toString());
                        tdText.setUid(tdSection.getUuid());
                        tdText.setBookname(tdBook.getBookname());
                        tdText.setSection(tdSection.getSectionname());
                        tdText.setAuthor(tdBook.getAuthorName());
                        tdText.setCreatetime(new Date());
                        tdText.setIsdelete(0);
                        tdText.setText(sysAuthText.getContent());
                        //保存
                        tdTextMapper.insert(tdText);
                        //修改章节属性并更新
                        int count = (" " + tdText.getText() + " ").split(regex).length - 1;
                        tdSection.setFontsize(count);
                        tdSectionMapper.updateByPrimaryKey(tdSection);
                    }


                }
                /*
                *===============================================================================================
                */

                    return R.ok().put("msg", "导入成功");
                }

        } catch (Exception e) {
            e.printStackTrace();
            authBookInfo.setStatus(3);
            authBookInfoDao.update(authBookInfo);
            return R.error("导入失败");
        }
    }
}
